<template>
	<div class="pageBox">
		<div class="formBox borderClass">
			<header class="addAgentFormTop">
				<div class="textB">
					单个设置总代分红比例
				</div>
				<!-- <div>
					<span class="textColor">*</span>
					{{ $t('common.add_dialog_tips') }}
				</div> -->
			</header>
			<div v-if="step === 'one'" class="form-content">
				<el-form
					ref="editForm"
					:model="formData"
					:rules="rules"
					label-width="230px"
					class="demo-formData"
				>
					<el-form-item
						:label="`${$t('common.choose_merchant')}:`"
						prop="merchantId"
					>
						<el-col :span="12">
							<merchant-select
								v-model="formData.merchantId"
								:placeholder="$t('common.please_choose')"
							></merchant-select>
						</el-col>
					</el-form-item>
					<el-form-item :label="'分红周期:'" prop="searchTime">
						<el-col :span="12">
							<el-date-picker
								v-model="searchTime"
								style="width: 100%"
								size="medium"
								:picker-options="pickerShortcutNew"
								format="yyyy-MM-dd"
								type="daterange"
								range-separator="-"
								:start-placeholder="$t('common.start_date')"
								:end-placeholder="$t('common.end_date')"
								align="right"
								:clearable="false"
								:default-time="defaultTime"
							></el-date-picker>
						</el-col>
					</el-form-item>
					<el-form-item :label="'总代账号:'" prop="username">
						<el-col :span="12">
							<el-input
								v-model="formData.username"
								:placeholder="$t('common.please_enter')"
							></el-input>
							<div class="redColor txtMsg" v-if="errorMsg">
								{{ errorMsg }}
							</div>
						</el-col>
						<el-button
							type="primary"
							:disabled="loading"
							style="margin-left: 15px;"
							@click="searchFn"
						>
							{{ $t('common.search') }}
						</el-button>
					</el-form-item>

					<!-- <AgentRebates
						ref="AgentRebates"
						:isEdit="true"
						:commissionModel="formData.commissionModel"
					/> -->
					<div style="margin:0 130px">
						<el-table
							style="width: 100%"
							class="small-size-table"
							show-summary
							:summary-method="
								(val) => handleRow(val, subSummary)
							"
							:data="tableData"
							border
						>
							<el-table-column
								prop="venueTypeName"
								label="场馆名称"
							></el-table-column>
							<el-table-column prop="winTotal" label="会员盈亏">
								<template slot-scope="scope">
									<span
										:style="
											handleNumberColor(
												scope.row.winAmount
											)
										"
									>
										{{ handleCurrency('USDT') }}
										{{
											handleNumber(
												'USDT',
												scope.row.winAmount
											)
										}}
									</span>
								</template>
							</el-table-column>
							<el-table-column
								prop="validBetTotal"
								label="有效投注"
							>
								<template slot-scope="scope">
									<span>
										{{ handleCurrency('USDT') }}
										{{
											handleNumber(
												'USDT',
												scope.row.validBetAmount
											)
										}}
									</span>
								</template>
							</el-table-column>
							<el-table-column
								prop="rebateAfter"
								label="有效盈余比"
							>
								<template slot-scope="scope">
									<span>
										{{
											handlePercentage(
												scope.row.surplusRate
											)
										}}
									</span>
								</template>
							</el-table-column>
							<el-table-column
								prop="rebateAfter"
								label="分红比例"
							>
								<template slot-scope="scope">
									<span class="flex-center">
										<el-input-number
											@change="
												inpNum($event, scope.$index)
											"
											:precision="2"
											v-input="{ name: 'float', num: '2' }"
											:controls="false"
											:min="0"
											:max="100"
											:placeholder="'0.00'"
											:value="scope.row.rate"
										/>
										<span>&nbsp;%</span>
									</span>
								</template>
							</el-table-column>
						</el-table>
					</div>

					<el-form-item style="margin-top: 15px">
						<el-button
							type="primary"
							:disabled="!tableData.length"
							@click="nextStep"
						>
							下一步
						</el-button>
						<!-- <el-button @click="resetForm('validateForm')">
							{{ $t('common.reset') }}
						</el-button> -->
					</el-form-item>
				</el-form>
			</div>
			<div v-else class="form-content">
				<el-form
					ref="validateForm"
					:model="formData2"
					:rules="rules2"
					label-width="230px"
					class="demo-formData form-box"
				>
					<!-- <el-form-item
						:label="`${$t('common.choose_merchant')}:`"
						prop="merchantId"
					>
						11
					</el-form-item> -->
					<el-form-item :label="'分红周期:'" prop="userName">
						<el-col :span="12">
							{{ startDate }}～{{ endDate }}
						</el-col>
					</el-form-item>
					<el-form-item :label="'总代账号:'" prop="userName">
						<el-col :span="12">
							{{ username }}
						</el-col>
					</el-form-item>

					<!-- <AgentRebates
						ref="AgentRebates"
						:isEdit="true"
						:commissionModel="formData.commissionModel"
					/> -->
					<div style="margin:0 130px;margin-bottom: 20px;">
						<el-table
							style="width: 100%"
							class="small-size-table"
							show-summary
							:summary-method="
								(val) => handleRow2(val, subSummary2)
							"
							:data="tableData2"
							border
						>
							<el-table-column
								prop="venueTypeName"
								label="场馆名称"
							></el-table-column>

							<el-table-column
								prop="validBetTotal"
								label="有效投注"
							>
								<template slot-scope="scope">
									<span>
										{{ handleCurrency('USDT') }}
										{{
											handleNumber(
												'USDT',
												scope.row.validBetAmount
											)
										}}
									</span>
								</template>
							</el-table-column>
							<el-table-column prop="rate" label="分红比例">
								<template slot-scope="scope">
									<span>
										{{ handlePercentage(scope.row.rate) }}
									</span>
								</template>
							</el-table-column>
							<el-table-column
								prop="platRate"
								label="平台占成比例"
							>
								<template slot-scope="scope">
									<span>
										{{
											handlePercentage(scope.row.platRate)
										}}
									</span>
								</template>
							</el-table-column>
							<el-table-column
								prop="amountTotal"
								label="应发分红"
							>
								<template slot-scope="scope">
									<span>
										{{ handleCurrency('USDT') }}
										{{
											handleNumber(
												'USDT',
												scope.row.amount
											)
										}}
									</span>
								</template>
							</el-table-column>
						</el-table>
					</div>

					<el-form-item :label="'本次实发分红:'" prop="actAmount">
						<el-col :span="12">
							<el-input-number
								v-model="formData2.actAmount"
								:placeholder="$t('common.please_enter')"
								:controls="false"
								v-input="{ name: 'float', num: '2' }"
								style="width: 420px;"
							></el-input-number>
							<span
								style="position: absolute;left: 4px;color: #909399;"
							>
								{{ handleCurrency('USDT', true) }}
							</span>
						</el-col>
					</el-form-item>

					<el-form-item style="margin-top: 15px">
						<el-button @click="prevStep">
							返回
						</el-button>
						<el-button
							type="primary"
							:disabled="loading"
							@click="submitFn"
						>
							确定
						</el-button>
						<!-- <el-button @click="resetForm('validateForm')">
							{{ $t('common.reset') }}
						</el-button> -->
					</el-form-item>
				</el-form>
			</div>
		</div>
		<GoogleKeyInput
			:isShowdialog="isShowdialog"
			@getGoogleKey="getGoogleKey($event)"
			@backPrevStep="backPrevStep()"
		></GoogleKeyInput>
		<el-dialog
			title=""
			:visible.sync="dialogVisible"
			top="40vh"
			width="30%"
		>
			<div style="text-align:center">
				<i
					class="el-icon-success"
					style="font-size: 48px;color: #67C23A;"
				></i>
				<h3>
					申请提交成功
				</h3>
				<p
					v-if="typeof orderNo === 'string'"
					style="display:flex;justify-content: center;"
				>
					{{ $t('funds.order_no') }}：
					<Copy :title="orderNo" :copy="copy">
						{{ orderNo }}
					</Copy>
					&nbsp;
					{{ $t('funds.capital_adjustment.waiting_audit_results') }}
				</p>
				<p style="text-align: left;" v-else>
					<span v-for="(item, index) of orderNo" :key="item">
						<template v-if="index < 2">
							<span>{{ $t('funds.order_no') }}：</span>
							<copyNo :title="item" :copy="copy">
								{{ item }}
							</copyNo>
						</template>
						<span v-if="index === 0">、</span>
					</span>
					&nbsp;
					<span>…等{{ orderNo.length }}条审核单，等待审核结果</span>
				</p>
				<br />
				<el-button
					type="primary"
					size="medium"
					@click="dialogVisibleFn"
				>
					{{ $t('common.back') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { rules, accountTypeArr } from './rules.js'
import summaryList from './summaryList'
import list from '@/mixins/list'
import md5 from 'js-md5'
import BusinessModelSelector from '@/components/Form/BusinessModelSelector.vue'
import dayjs from 'dayjs'
import AgentRebates from '@/components/AgentRebates'
import copyNo from './copyNo.vue'
const end = () => {
	return dayjs()
		.endOf('day')
		.subtract(1, 'd')
}
const start = () => {
	return dayjs()
		.startOf('day')
		.subtract(1, 'd')
}
// const shortcut2 = [
// 	{
// 		text: i18n.t('common.utils.yesterday'),
// 		onClick(picker) {
// 			const end = dayjs()
// 				.endOf('day')
// 				.subtract(1, 'd')
// 			const start = dayjs()
// 				.startOf('day')
// 				.subtract(1, 'd')
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	},
// 	{
// 		text: i18n.t('common.utils.last_week'),
// 		onClick(picker) {
// 			let start, end
// 			const weekNum = dayjs().day()
// 			if (weekNum === 0) {
// 				end = dayjs()
// 					.subtract(2, 'week')
// 					.endOf('week')
// 					.add(1, 'day')
// 				start = dayjs()
// 					.subtract(2, 'week')
// 					.startOf('week')
// 					.add(1, 'day')
// 			} else {
// 				end = dayjs()
// 					.subtract(1, 'week')
// 					.endOf('week')
// 					.subtract(-1, 'day')
// 				start = dayjs()
// 					.startOf('week')
// 					.subtract(1, 'week')
// 					.subtract(-1, 'day')
// 			}
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	},
// 	{
// 		text: i18n.t('common.utils.week_now'),
// 		onClick(picker) {
// 			let start, end
// 			const weekNum = dayjs().day()
// 			if (weekNum === 0) {
// 				end = dayjs().endOf('day')
// 				start = dayjs()
// 					.subtract(1, 'd')
// 					.startOf('week')
// 					.startOf('day')
// 					.add(1, 'd')
// 			} else {
// 				end = dayjs().endOf('day')
// 				start = dayjs()
// 					.startOf('day')
// 					.startOf('week')
// 					.add(1, 'd')
// 			}
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	},
// 	{
// 		text: i18n.t('common.utils.last_month'),
// 		onClick(picker) {
// 			const end = dayjs()
// 				.subtract(1, 'month')
// 				.endOf('month')
// 			const start = dayjs()
// 				.startOf('month')
// 				.subtract(1, 'month')
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	},
// 	{
// 		text: i18n.t('common.utils.month1'),
// 		onClick(picker) {
// 			const end = dayjs().endOf('day')
// 			const start = dayjs().startOf('month')
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	},
// 	{
// 		text: i18n.t('common.utils.week1'),
// 		onClick(picker) {
// 			const end = dayjs().endOf('day')
// 			const start = dayjs()
// 				.startOf('day')
// 				.subtract(6, 'day')
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	},
// 	{
// 		text: i18n.t('common.utils.month1_recent'),
// 		onClick(picker) {
// 			const end = dayjs().endOf('day')
// 			const start = dayjs()
// 				.startOf('day')
// 				.subtract(29, 'day')
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	},
// 	{
// 		text: i18n.t('common.utils.month3_recent'),
// 		onClick(picker) {
// 			const end = dayjs().endOf('day')
// 			const start = dayjs()
// 				.startOf('day')
// 				.subtract(89, 'day')
// 			picker.$emit('pick', [+start, +end])
// 		}
// 	}
// ]
export default {
	name: 'TotalAgent',
	components: {
		AgentRebates,
		copyNo,
		GoogleKeyInput: () => import('@/components/GoogleKeyInput'),
		BusinessModelSelector
	},
	mixins: [list, summaryList],
	props: {
		agentLevel: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			loading: false,
			step: 'one',
			dialogVisible: false,
			errorMsg: '',
			isShowdialog: false,
			merchantId: '',
			tableData: [],
			tableData2: [],
			startDate: '',
			startDate2: '',
			subSummary2: {},
			endDate: '',
			username: '',
			endDate2: '',
			orderNo: '',
			subSummary: {},
			searchTime: [start(), end()],
			formData: {},
			formData2: {}
		}
	},
	computed: {
		pickerShortcutNew() {
			const _this = this
			return {
				disabledDate(time) {
					const now = dayjs()
						.endOf('day')
						.subtract(1, 'd')
					return time.getTime() > now
				},
				onPick({ maxDate, minDate }) {
					if (!maxDate) {
						_this.minDate = minDate
					}
				}
				// shortcuts: shortcut2
			}
		},
		appIdArr() {
			return this.globalDics.appId || []
		},
		rules() {
			return {
				merchantId: [
					{
						required: true,
						message: '请选择商户',
						trigger: ['change', 'blur']
					}
				],
				username: [
					{
						required: true,
						message: '请输入总代账号',
						trigger: ['change', 'blur']
					}
				]
			}
		},
		rules2() {
			return {
				actAmount: [
					{
						required: true,
						message: '请输入总代账号',
						trigger: ['change', 'blur']
					}
				]
			}
		},
		accountTypeArr
	},
	watch: {
		// 处理页面缓存问题
		$route: {
			handler(route) {
				this.resetForm()
			},
			deep: true,
			immediate: true
		}
	},
	methods: {
		inpNum(val, index) {
			this.$set(this.tableData[index], 'rate', val || 0)
		},

		getGoogleKey(data) {
			const params = {
				...this.formData2,
				items: this.tableData2,
				startDate: this.startDate2,
				endDate: this.endDate2,
				username: this.username,
				googleVerifyCode: data,
				amount: this.subSummary2.amountTotal,
				merchantId: this.merchantId
			}
			this.$api
				.dividendApply(params)
				.then((res) => {
					if (res?.code === 200) {
						this.dialogVisible = true
						this.orderNo = res.data

						this.isShowdialog = false
					}
				})
				.catch((err, d) => {
					this.errorMsg = String(err).replace('Error: ', '')
				})
		},
		backPrevStep() {
			this.isShowdialog = false
		},
		submitFn() {
			this.isShowdialog = true
		},
		searchFn() {
			this.errorMsg = null
			this.$refs.editForm.validate((valid) => {
				if (!valid) {
					return
				}
				const timeArr = this.searchTime || []
				const params = {
					...this.formData,
					startDate: dayjs(timeArr[0]).format('YYYY-MM-DD'),
					endDate: dayjs(timeArr[1]).format('YYYY-MM-DD')
				}
				this.$api
					.getProxyDividendInfo(params)
					.then((res) => {
						if (res?.code === 200) {
							this.tableData = res.data?.items || []
							this.tableData.forEach((ele) => {
								ele.rate = 0
							})
							this.subSummary = {
								validBetTotal: res?.data?.validBetTotal,
								winTotal: res?.data?.winTotal
							}
							console.log(this.subSummary, 'asdoasdoi')
						} else {
							this.errorMsg = res.msg
						}
					})
					.catch((err, d) => {
						this.errorMsg = String(err).replace('Error: ', '')
					})
			})
		},
		formatParams() {
			const params = {
				...this.formData,
				rebateAllotMode: 1,
				...(this.formData.commissionModel === 1
					? {
							rebateRateList: this.$refs[
								'AgentRebates'
							].getValues()
					  }
					: {
							commissionRateList: this.$refs[
								'AgentRebates'
							].getValues(['commissionDzRebates']),
							rebateRateList: this.$refs[
								'AgentRebates'
							].getValues(['memberPlatform'])
					  })
			}
			params.password = `${md5(
				md5(params.password).toUpperCase()
			).toUpperCase()}`
			return params
		},
		async resetForm() {
			await this.$refs['validateForm'].resetFields()
			await this.$refs['AgentRebates'].resetFields()

			this.$refs['AgentRebates'].clearValidate('rebateRateTemplateId')
		},
		async validate() {
			return Promise.all([
				new Promise((resolve, reject) => {
					this.$refs['AgentRebates'].validate((err) => {
						if (err) {
							return resolve()
						}

						return reject()
					})
				}),
				new Promise((resolve, reject) => {
					this.$refs['validateForm'].validate((err) => {
						if (err) {
							return resolve()
						}
						return reject()
					})
				})
			])
		},
		prevStep() {
			this.step = 'one'
		},
		dialogVisibleFn() {
			this.dialogVisible = false
			this.step = 'one'
		},
		nextStep() {
			this.errorMsg = null
			this.$refs.editForm.validate((valid) => {
				if (!valid) {
					return
				}
				const timeArr = this.searchTime || []
				const params = {
					...this.formData,
					items: this.tableData,
					startDate: dayjs(timeArr[0]).format('YYYY-MM-DD'),
					endDate: dayjs(timeArr[1]).format('YYYY-MM-DD')
				}
				this.$api
					.getCalculateDividend(params)
					.then((res) => {
						if (res?.code === 200) {
							this.startDate = dayjs(timeArr[0]).format(
								'YYYY/MM/DD'
							)
							this.endDate = dayjs(timeArr[1]).format(
								'YYYY/MM/DD'
							)
							this.startDate2 = dayjs(timeArr[0]).format(
								'YYYY-MM-DD'
							)
							this.endDate2 = dayjs(timeArr[1]).format(
								'YYYY-MM-DD'
							)
							this.merchantId = this.formData.merchantId
							this.username = this.formData.username
							this.tableData2 = res.data?.items || []

							this.subSummary2 = {
								amountTotal: res?.data?.amountTotal,
								validBetTotal: res?.data?.validBetTotal
							}
							function truncateToTwoDecimalPlaces(num) {
								return Math.floor(num * 100) / 100
							}
							var result = truncateToTwoDecimalPlaces(
								res?.data?.amountTotal || 0
							)

							this.formData2.actAmount = result
							this.step = 'tow'
						} else {
							this.errorMsg = res.msg
						}
					})
					.catch((err, d) => {
						this.errorMsg = String(err).replace('Error: ', '')
					})
			})
		}
	}
}
</script>
<style lang="scss" scoped>
.formBox {
	padding-bottom: 30px;
	background: #ffffff;
	border: 1px solid #e4e7ed;
	.demo-formData {
		margin: 30px auto 20px;
		.el-select {
			width: 100%;
		}
	}
}

.vi_VN,
.en_US {
	.formBox .demo-formData {
		width: 640px;
	}

	.el-tab-pane {
		overflow: auto;
	}

	.table-wrapper {
		width: 1700px;
	}
}

::v-deep .add-table th.el-table__cell {
	color: #909399;
	font-weight: 700;
	padding: 0;
}
::v-deep .add-table .el-table__row:hover > td.el-table__cell {
	background-color: #fff !important;
}

::v-deep .add-table {
	.el-input-number__decrease {
		display: none;
	}
	.el-input-number__increase {
		display: none;
	}

	.el-input-number .el-input__inner {
		padding: 0;
	}

	.el-input-number {
		width: 80px;
	}
	.el-form-item {
		margin-bottom: 15px;
	}
	.el-form-item__error {
		white-space: nowrap;
	}
}

.form-content {
	align-items: center;
}

::v-deep .form-box {
	.el-input-number .el-input__inner {
		text-align: left;
	}
}

::v-deep .current_spetify_item {
	position: relative;
	label.el-form-item__label::before {
		content: '*';
		color: #f56c6c;
		display: inline-box;
		font-size: 14px;
		font-weight: 700;
		margin-right: 5px;
	}
}

.txtMsg {
	font-size: 12px;
	position: absolute;
	bottom: -15px;
	background: #fff;
	z-index: 1;
	height: 10px;
	line-height: 10px;
}
</style>
